package com.xunqi.interceptor;

import java.time.LocalDateTime;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xunqi.dao.cluster.ICommonAccessLogDao;
import com.xunqi.dao.master.ICityDao;
import com.xunqi.domain.CommonAccessLog;
import com.xunqi.util.IdGenerateUtil;
import com.xunqi.util.RequestUtil;

public class CommonIntercepter implements HandlerInterceptor {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private ICommonAccessLogDao commonAccessLogDao;
	@Autowired
	private ICityDao cityDao;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		request.setAttribute("intercepterPreTime", System.currentTimeMillis());
		// TODO set ip
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv)
			throws Exception {
		request.setAttribute("intercepterPostTime", System.currentTimeMillis());
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
			Exception exception) throws Exception {
		// TODO insert into DB
		long intercepterPreTime = (long) request.getAttribute("intercepterPreTime");
		long intercepterPostTime = (long) request.getAttribute("intercepterPostTime");
		long intercepterAfterTime = System.currentTimeMillis();
		logger.info(
				"preTime:[{}],postTime[{}],afterTime[{}],after-pre[{}],servletPath[{}],requestURL[{}],parameterMap[{}]",
				intercepterPreTime, intercepterPostTime, intercepterAfterTime,
				(intercepterAfterTime - intercepterPreTime), request.getServletPath(), request.getRequestURL(),
				RequestUtil.getAllParameterToString(request));
		commonAccessLogDao.saveCommonAccessLog(new CommonAccessLog(IdGenerateUtil.generateIdByTimeStamp(),
				request.getRequestURI(), RequestUtil.getAllParameterToString(request), "",
				(intercepterAfterTime - intercepterPreTime), LocalDateTime.now()));
	}

}
